package com.zxjbyte.yiyi.framework.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zxjbyte.yiyi.framework.common.util.AuthUtil;
import com.zxjbyte.yiyi.framework.mybatis.base.BasePO;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * @Author zhangxingjia
 * @Date 2023/3/2 17:56
 * @Version: 1.0
 */
public class YiyiMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BasePO) {
            BasePO basePO = (BasePO) metaObject.getOriginalObject();
            Date now = new Date();

            if(ObjectUtil.isNull(basePO.getCreateTime())){
                basePO.setCreateTime(now);
            }

            if(ObjectUtil.isNull(basePO.getUpdateTime())){
                basePO.setUpdateTime(now);
            }

            String userId = AuthUtil.getUserIdAsStr();
            if (StrUtil.isNotEmpty(userId) && StrUtil.isBlank(basePO.getCreateUser())) {
                basePO.setCreateUser(userId);
            }

            if (StrUtil.isNotEmpty(userId) && StrUtil.isBlank(basePO.getUpdateUser())) {
                basePO.setUpdateUser(userId);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BasePO) {
            BasePO basePO = (BasePO) metaObject.getOriginalObject();
            if(ObjectUtil.isNull(basePO.getUpdateTime())){
                basePO.setUpdateTime(new Date());
            }

            String userId = AuthUtil.getUserIdAsStr();
            if(StrUtil.isNotEmpty(userId) && StrUtil.isBlank(basePO.getUpdateUser())){
                basePO.setUpdateUser(userId);
            }
        }
    }
}
